#!/usr/bin/env bash

# 打印颜色控制
color()
{
  local codes=()
  if [ "$1" = 'bold' ]; then
    codes=( "${codes[@]}" '1' )
    shift
  fi
  if [ "$#" -gt 0 ]; then
    local code=
    case "$1" in
      # see https://en.wikipedia.org/wiki/ANSI_escape_code#Colors
      black) code=30 ;;
      red) code=31 ;;
      green) code=32 ;;
      yellow) code=33 ;;
      blue) code=34 ;;
      magenta) code=35 ;;
      cyan) code=36 ;;
      white) code=37 ;;
    esac
    if [ "$code" ]; then
      codes=( "${codes[@]}" "$code" )
    fi
  fi
  local IFS=';'
  echo -en '\033['"${codes[*]}"'m'
}

# 带颜色打印
wrap_color()
{
  text="$1"
  shift
  color "$@"
  echo -n "$text"
  color reset
  echo
}

# 打印消息：NOTICE：××××
wrap_notice() {
	echo -e "$(wrap_color NOTICE bold white): $(wrap_color "$1" bold yellow)"
}

# 打印消息：INFO：××××
wrap_info() {
 	echo -e "$(wrap_color INFO bold white): $(wrap_color "$1" bold blue)"
}

# 打印消息：ERROR：××××
wrap_error() {
   echo -e "$(wrap_color ERROR bold white): $(wrap_color "$1" bold red)"
}

# 打印消息：DEBUG：××××
wrap_debug() {
 	echo -e "$(wrap_color DEBUG bold green): $(wrap_color "$1" bold red)"
}

# 打印白色文字
wrap_string(){
 	echo -e "$(wrap_color "$1" bold white)"
}

# 打印蓝色文字
wrap_progress_string(){
 	echo -e "$(wrap_color "$1" bold blue)"
}

# 打印黄色文字
wrap_warning_string() {
  	echo -e "$(wrap_color "$1" bold yellow)"
}
wrap_risk_string() {
  	echo -e "$(wrap_color "$1" bold red)"
}

# 以下是一些功能前缀
#用法： [功能前缀] [带颜色打印]
# 保持底部有一个空行
KEEP_LINE()
{
	printf "\n\n\033[1A"
	${@:1:$#-1} "${!#}\c"
}
# 返回上一行打印
BACK_LINE()
{
	printf "\033[s\033[1A\r\033[K"
	${@:1:$#-1} "${!#}\c"
	printf "\033[u"
}
# 在下一行打印
NEXT_LINE()
{
	printf "\033[s\033[1B\r\033[K"
	${@:1:$#-1} "${!#}\c"
	printf "\033[u"
}

# 闪烁
FLASH_LINE()
{
	${@:1:$#-1} "\033[5m${!#}"
}
# 打印等待标志
function print_wait()
{
	sp='/-\|'
	touch ${PRINT_WAITING_FILE}
	while [[ -f ${PRINT_WAITING_FILE} ]]; do
		printf '\b%.1s\033[?25l' "$sp"
		sp=${sp#?}${sp%???}
		read -rt 0.1 <> <(:) || :
	done
	printf "\r\033[?25h"
}
# 停止等待
function stop_print_wait()
{
	rm -rf ${PRINT_WAITING_FILE} &>/dev/null
	# Sleep 0.2s waits for the print_wait process to exit.
	system_sleep 0.2
}
# 打印等待
WAIT_LINE()
{
	${@:1:$#-1} "${!#} "
	(print_wait &)
}
# 停止等待
WAIT_STOP()
{
	stop_print_wait
}

module_init()
{
    # 设置环境变量
    export PRINT_CTRL_DIR="${TmpDir}/module/print_control"
    export PRINT_WAITING_FILE="${PRINT_CTRL_DIR}/.print_waitting"
    # 创建临时文件夹
    [[ -d ${PRINT_CTRL_DIR} ]] || mkdir -p ${PRINT_CTRL_DIR}
    debug_echo "Print module is ok!"
}

module_exit()
{
    # 停止等待
    stop_print_wait
    # 恢复颜色
    color reset
    # 回复光标显示
    printf "\033[?25h"
    # 删除临时文件夹
    rm -rf ${PRINT_CTRL_DIR}
    # 删除环境变量
    unset PRINT_CTRL_DIR
    unset PRINT_WAITING_FILE
    debug_echo "Print module exited!"
}